﻿// Josh Smith - MS-PL

using System;
using System.Diagnostics;
using System.Windows.Input;

namespace FluentViewModel
{
    internal class RelayCommand : ICommand
    {
        private readonly Action execute;
        private readonly Func<bool> canExecute;

        public RelayCommand(Action execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            this.execute = execute;
            this.canExecute = canExecute;
        }

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return canExecute == null
                ? true
                : canExecute();
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (canExecute != null)
                    CommandManager.RequerySuggested += value;
            }

            remove
            {
                if (canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        public void Execute(object parameter)
        {
            execute();
        }
    }
    
    //public class RelayCommand<TParameter> : ICommand
    //{
    //    private readonly Action<TParameter> execute;
    //    private readonly Predicate<TParameter> canExecute;

    //    public RelayCommand(Action<TParameter> execute)
    //        : this(execute, null)
    //    {
    //    }

    //    public RelayCommand(Action<TParameter> execute, Predicate<TParameter> canExecute)
    //    {
    //        this.execute = execute;
    //        this.canExecute = canExecute;
    //    }

    //    [DebuggerStepThrough]
    //    public bool CanExecute(object parameter)
    //    {
    //        return canExecute == null 
    //            ? true
    //            : canExecute((TParameter)parameter);
    //    }

    //    public event EventHandler CanExecuteChanged
    //    {
    //        add
    //        {
    //            if (canExecute != null)
    //                CommandManager.RequerySuggested += value;
    //        }

    //        remove
    //        {
    //            if (canExecute != null)
    //                CommandManager.RequerySuggested -= value;
    //        }
    //    }

    //    public void Execute(object parameter)
    //    {
    //        if (parameter == null)
    //            return;
    //        execute((TParameter)parameter);
    //    }
    //}
}